import asyncio

class TaskManager:
    def __init__(self):
        self.tasks = {}

    async def start_task(self, name, coro_func):
        if name in self.tasks:
            print(f"任务 {name} 已存在，先停止")
            await self.stop_task(name)

        print(f"启动任务 {name}")
        task = asyncio.create_task(coro_func())
        self.tasks[name] = task

    async def stop_task(self, name):
        if name in self.tasks:
            print(f"停止任务 {name}")
            self.tasks[name].cancel()
            try:
                await self.tasks[name]
            except asyncio.CancelledError:
                print(f"任务 {name} 已取消")
            del self.tasks[name]

    async def stop_all(self):
        print("停止所有后台任务")
        for name in list(self.tasks.keys()):
            await self.stop_task(name)

task_manager = TaskManager()